import React, { useEffect } from 'react';
import { Layout as AntLayout, Menu, Avatar, Dropdown, Divider, Badge } from 'antd';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import {
  HomeOutlined,
  LineChartOutlined,
  CalculatorOutlined,
  TrophyOutlined,
  CheckSquareOutlined,
  UserOutlined,
  LogoutOutlined,
  GlobalOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import { useUserStore } from '../store/userStore';
import { getTodayRandomTasks } from '../data/environmentalTasks';

const { Header, Content, Sider, Footer } = AntLayout;

const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { user, logout } = useUserStore();
  const location = useLocation();
  const navigate = useNavigate();

  // 检查是否需要刷新每日任务
  useEffect(() => {
    const today = new Date().toISOString().split('T')[0];
    const storedDate = localStorage.getItem('lastTaskRefreshDate');
    
    // 如果今天尚未刷新任务，设置标记以便在任务页面刷新
    if (storedDate !== today) {
      localStorage.setItem('needsTaskRefresh', 'true');
    }
  }, []);

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const userMenu = (
    <Menu>
      <Menu.Item key="profile" icon={<UserOutlined />}>
        <Link to="/profile">个人资料</Link>
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout" icon={<LogoutOutlined />} onClick={handleLogout}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  // 获取当前路由路径
  const currentPath = location.pathname;

  // 侧边菜单项配置
  const menuItems = [
    {
      key: '/dashboard/planet',
      icon: <GlobalOutlined />,
      label: <Link to="/dashboard/planet">我的星球</Link>,
    },
    {
      key: '/dashboard/calculator',
      icon: <CalculatorOutlined />,
      label: <Link to="/dashboard/calculator">碳足迹计算</Link>,
    },
    {
      key: '/dashboard/challenges',
      icon: <TrophyOutlined />,
      label: <Link to="/dashboard/challenges">个性化挑战</Link>,
    },
    {
      key: '/dashboard/tasks',
      icon: <CheckSquareOutlined />,
      label: (
        <Link to="/dashboard/tasks">
          <Badge dot={localStorage.getItem('needsTaskRefresh') === 'true'}>
            环保任务
          </Badge>
        </Link>
      ),
    },
    {
      key: '/dashboard/data',
      icon: <LineChartOutlined />,
      label: <Link to="/dashboard/data">数据中心</Link>,
    },
    // 分隔线
    {
      type: 'divider' as const,
    },
    // 绿色能量显示
    {
      key: 'green-energy',
      icon: <ThunderboltOutlined style={{ color: '#52c41a' }} />,
      label: (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span>绿色能量</span>
          <span 
            style={{ 
              backgroundColor: '#52c41a', 
              color: 'white', 
              padding: '0px 8px', 
              borderRadius: 10,
              fontWeight: 'bold',
              fontSize: 13,
              marginLeft: 8
            }}
          >
            {user?.greenEnergy || 0}
          </span>
        </div>
      ),
    },
  ];

  return (
    <AntLayout style={{ minHeight: '100vh' }}>
      <Header style={{ 
        display: 'flex', 
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingInline: 20,
        backgroundColor: '#fff',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <div className="logo" style={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: 8,
          fontSize: 18,
          fontWeight: 'bold'
        }}>
          <GlobalOutlined style={{ color: '#52c41a', fontSize: 22 }} />
          碳星球
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Dropdown overlay={userMenu} trigger={['click']}>
            <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Avatar icon={<UserOutlined />} />
              <span>{user?.username || '用户'}</span>
            </div>
          </Dropdown>
        </div>
      </Header>
      <AntLayout>
        <Sider width={200} style={{ background: '#fff' }}>
          <Menu
            mode="inline"
            selectedKeys={[currentPath]}
            style={{ height: '100%', borderRight: 0 }}
            items={menuItems}
          />
        </Sider>
        <AntLayout style={{ padding: '0 24px 24px' }}>
          <Content
            style={{
              padding: 24,
              margin: 0,
              minHeight: 280,
              background: '#fff',
              borderRadius: 8,
              marginTop: 24
            }}
          >
            {children}
          </Content>
        </AntLayout>
      </AntLayout>
    </AntLayout>
  );
};

export default Layout; 